import React from 'react';
import LzEditor from 'react-lz-editor/editor'
import {connect} from 'dva';

class RichTextEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      responseList: []
    };
  }

  receiveRaw = (content) => {
    this.setState({responseList: []});
    //更新内容
    this.props.updateContent(content);
  };
  onChange = (info) => {
    let currFileList = info.fileList;
    currFileList = currFileList.map((file) => {
      if (file.response) {
        // 组件会将 file.url 作为链接进行展示
        file.url = file.response.data;
      }
      return file;
    });

    //按照服务器返回信息筛选成功上传的文件
    currFileList = currFileList.filter((file,index, array) => {
      if((index+1)===array.length){
        return file.response || (file.url && file.status == "done") || file.status == "uploading";
      }else{
        return false;
      }
    });
    if (currFileList && currFileList.length != 0) {
      this.setState({responseList: currFileList});
    }
    this.forceUpdate();
  };

  render() {
    const uploadProps = {
      name: 'file',
      action: "/api/system/file/upload?accessToken=" + JSON.parse(window.sessionStorage.getItem("accessToken")),
      onChange: this.onChange,
      listType: 'picture',
      fileList: this.state.responseList,
      showUploadList: false,
    };
    return (
      <div>
        <LzEditor
          active={true}
          importContent={this.props.htmlContent}
          cbReceiver={this.receiveRaw}
          uploadProps={uploadProps}
          video={false}
          audio={false}
          autoSave={false}
        />
      </div>
    );
  }
}

export default connect()(RichTextEditor);
